package com.zy.mc_module.ui.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.zy.mc_module.R;
import com.zy.mc_module.base.App;
import com.zy.mc_module.base.kotlin.BaseActivity;
import com.zy.mc_module.databinding.ActivityRegisterBinding;
import com.zy.mc_module.databinding.DialogCheckImgCodeBinding;
import com.zy.mc_module.mvp.bean.BaseBean;
import com.zy.mc_module.mvp.bean.ProtocolBean;
import com.zy.mc_module.mvp.bean.UserBean;
import com.zy.mc_module.mvp.contract.LoginContract;
import com.zy.mc_module.mvp.presenter.LoginPresenter;
import com.zy.mc_module.ui.main.AgreementActivity;
import com.zy.mc_module.utils.DateUtil;
import com.zy.mc_module.utils.GlideUtil;
import com.zy.mc_module.utils.NoDoubleUtil;
import com.zy.mc_module.utils.StatusBarUtil;
import com.zy.mc_module.utils.StringsUtils;
import com.zy.mc_module.utils.ToastUtil;
import com.zy.mc_module.view.ClearEditText;
import com.zy.mc_module.view.CustomHeadLayout;
import com.zy.mc_module.utils.retrofit.error.ThdException;
import com.zy.mc_module.wheel.dialog.CommonDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

/**
 * @Date 19/3/16
 * @Author dq
 * 注册界面
 */
public class RegisterActivity extends BaseActivity<LoginContract.View, LoginPresenter, ActivityRegisterBinding> implements
        LoginContract.View {

    ClearEditText et_tel;
    CheckBox agreeBox;
    private CommonDialog checkDialog;
    private DialogCheckImgCodeBinding dialogBinding;
    private String tel;
    private String registProtocol;
    private String title;
    private String imgCode;


    @Override
    public LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @NonNull
    @Override
    public ActivityRegisterBinding getViewBinding() {
        return ActivityRegisterBinding.inflate(getLayoutInflater());
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        App.getInstance().addTmpActivity(this);
        StatusBarUtil.setImmersiveStatusBar(this);

        et_tel = binding.loginTel;
        agreeBox = binding.loginAgreeBox;
        dialogBinding = DialogCheckImgCodeBinding.inflate(getLayoutInflater());
        checkDialog = new CommonDialog(context, false, dialogBinding.getRoot());
        getPresenter().queryArticleProtocol(context, "13", "1");//注册协议
    }

    @Override
    protected void initListener() {
        super.initListener();
        binding.loginSure.setEnabled(false);
        binding.customhead.setLeftClickListener(view -> finish());
        binding.loginSure.setOnClickListener(this::login);
        binding.loginTel.addMyTextChangedListener(s -> {
            binding.loginSure.setEnabled(false);
            if (s.length() == 11) {
                if (StringsUtils.isPhoneNum(s.toString())) {
                    binding.loginSure.setEnabled(true);
                } else {
                    ToastUtil.show("请输入正确的手机号获取验证码");
                }
            }
        });
        binding.loginAgreement.setOnClickListener(this::onViewClicked);
        binding.registProtocol.setOnClickListener(this::onViewClicked);

        setDialogListener();
    }

    private void setDialogListener() {

        dialogBinding.dialogHintSwitch.setOnClickListener(v -> {
            getImgCode();
        });
        dialogBinding.hintCancel.setOnClickListener(v -> checkDialog.dismiss());
        dialogBinding.hintSure.setOnClickListener(v -> {
            String code = dialogBinding.hintContent.getText().toString();
            if (StringsUtils.isEmpty(code)) {
                ToastUtil.show("请输入验证码");
                return;
            }
            getPresenter().getRegisterCode(context, et_tel.getText().toString(), code);
        });
    }

    private void getImgCode() {
        if (NoDoubleUtil.isFastClick())
            getPresenter().getImgCode(context, tel);
    }

    public void login(View view) {
        tel = et_tel.getText().toString().trim();
        if (!agreeBox.isChecked()) {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            View v = getWindow().peekDecorView();
            if (null != v) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
            ToastUtil.show("请阅读并同意《注册协议》和《隐私注册》");
            return;
        }
        if (!StringsUtils.isPhoneNum(tel)) {
            ToastUtil.show("请输入正确的手机号获取验证码");
            return;
        }
        if (imgCode == null) {
            getImgCode();
        }else {
            getPresenter().getRegisterCode(context, et_tel.getText().toString(), imgCode);
        }
        //getPresenter().checkPhoneRegister(context, tel);
    }

    /***
     * 重新获取验证码
     */
    @Override
    public void onGetCodeSuccess(String success) {
        if (checkDialog.isShowing())
            checkDialog.dismiss();
        Intent intent = new Intent(context, VerCodeActivity.class);
        intent.putExtra("tel", tel);
        intent.putExtra("title", "注册");
        startActivity(intent);
    }

    @Override
    public void onLoginSuccess(UserBean userBean) {

    }

    @Override
    public void onSuccess(boolean isSuc) {

    }

    @Override
    public <T> void onSuccess(T t, int type) {
        if (type == LoginPresenter.IMG_CODE) {
            ResponseBody body = (ResponseBody) t;
            try {
                InputStream byteStream = body.byteStream();
                Bitmap bitmap = BitmapFactory.decodeStream(byteStream);
                GlideUtil.displayImage(dialogBinding.dialogHintImg,bitmap,R.mipmap.uvv_on_error);
                if (!checkDialog.isShowing()) {
                    checkDialog.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (type == 1) {
            BaseBean<Boolean> baseBean = (BaseBean<Boolean>) t;
            if (baseBean.data) {
                //下一步-获取验证码
                tel = et_tel.getText().toString().trim();
                getPresenter().getCode(context, "2", tel);
            } else {
                ToastUtil.showShort("手机号已注册");
            }
        } else if (type == 2) {
            ProtocolBean protocolBean = (ProtocolBean) t;
            if (!StringsUtils.isEmpty(protocolBean)) {
                if (!StringsUtils.isEmpty(registProtocol)) {
                    title = protocolBean.title;
                    //设置协议和点击事件
                    binding.loginAgreement.setText("《" + registProtocol + "》");
                    binding.registProtocol.setText("《" + title + "》");
                } else {
                    registProtocol = protocolBean.title;//注册协议
                    getPresenter().queryArticleProtocol(context, "14", "1");//隐私政策
                }

            }
        }
    }

    @Override
    public void onError(ThdException error) {
        imgCode = null;
        ToastUtil.showShort(error.message);
    }

    /**
     * 用户协议/隐私政策
     */
    public void onViewClicked(View view) {
        Intent intent = new Intent(context, AgreementActivity.class);
        switch (view.getId()) {
            case R.id.login_agreement:
                intent.putExtra("articleProtocolType", "13");
                intent.putExtra("title", registProtocol);
                break;
            case R.id.registProtocol:
                intent.putExtra("articleProtocolType", "14");
                intent.putExtra("title", title);
                break;
        }
        startActivity(intent);
    }
}
